package cn.thr.pethome.login.controller;

import cn.thr.pethome.constants.BaseConstants;
import cn.thr.pethome.login.domain.PhoneRegister;
import cn.thr.pethome.user.domain.User;
import cn.thr.pethome.user.service.IUserService;
import cn.thr.pethome.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/register")
//这里是说明你这个类是干什么用的
@Api(value = "注册API",description="注册的功能")
public class RegisterController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IUserService userService;

    @ApiOperation(value = "手机号注册")
    @PostMapping("/phone")
    public AjaxResult register(@RequestBody PhoneRegister register){
        //验证手机号验证码是否为null
        if(register.getPhone() == null || "".equals(register.getPhone().trim())){
            return AjaxResult.error().setMsg("手机号不能为空");
        }
        if(register.getPhoneCode() == null || "".equals(register.getPhoneCode().trim()) ){
            return AjaxResult.error().setMsg("手机号不能为空");
        }

        //校验两次密码是否相同 和 不为null 和 ""
        String password = register.getPassword();
        String passwordRepeat = register.getPasswordRepeat();
        if(password==null || "".equals(password.trim())){
            return AjaxResult.error().setMsg("密码不能为空");
        }
        if(passwordRepeat==null || "".equals(passwordRepeat.trim())){
            return AjaxResult.error().setMsg("确认密码不能为空");
        }
        if(!password.equals(passwordRepeat)){
            return AjaxResult.error().setMsg("两次密码不一致");
        }
        //验证手机号验证码是否正确
        String key = register.getPhone()+ BaseConstants.Vocode.REGISTER;

        Object value = redisTemplate.opsForValue().get(key);
        if(value == null){
            return AjaxResult.error().setMsg("你的手机号验证码已过期");
        }
        if(!register.getPhoneCode().equals(value.toString())){
            return AjaxResult.error().setMsg("手机号验证码输入错误");
        }
        User byPhone = userService.findByPhone(register.getPhone());
        if(byPhone != null){
            return AjaxResult.error().setMsg("该手机已被注册请登录或者忘记密码");
        }
        userService.add(register);
        return AjaxResult.success().setMsg("注册成功");
    }

}
